<template>
  <div class="containers" ref="content">
    <el-header class="header">
      <el-row>
        <el-button type="primary" plain icon="el-icon-s-order" @click="saveMyDiagram">保存</el-button>
        <el-button type="primary" plain icon="el-icon-download" @click="setEncoded('xml')">下载XML</el-button>
        <el-button ref="saveSvg" type="primary" plain icon="el-icon-download" @click="setEncoded('svg')">下载SVG</el-button>
      </el-row>
    </el-header>
    <div class="canvas" ref="canvas"></div>
    <div id="js-properties-panel" class="panel"></div>
  </div>
</template>

<script>
  // 引入相关的依赖
  import 'bpmn-js'
  import BpmnModeler from 'bpmn-js/lib/Modeler'
  import propertiesPanelModule from 'bpmn-js-properties-panel'
  import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'
  import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda'
  import customTranslate from '../../bpmnChineseTranslate'
  export default {
    data () {
      return {
        // bpmn建模器
        bpmnModeler: null,
        container: null,
        canvas: null,
        xmlStrSvg: null,
        xmlStrXml: null
      }
    },
    methods: {
      createNewDiagram () {
        // const bpmnXmlStr = this.$route.query.fileName;
        const bpmnXmlStr = '<?xml version="1.0" encoding="UTF-8"?>\n' +
                        '<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" targetNamespace="" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL http://www.omg.org/spec/BPMN/2.0/20100501/BPMN20.xsd">\n' +
                        '  <process id="Process_1ape15a" />\n' +
                        '  <bpmndi:BPMNDiagram id="sid-74620812-92c4-44e5-949c-aa47393d3830">\n' +
                        '    <bpmndi:BPMNPlane id="sid-cdcae759-2af7-4a6d-bd02-53f3352a731d" bpmnElement="Process_1ape15a" />\n' +
                        '    <bpmndi:BPMNLabelStyle id="sid-e0502d32-f8d1-41cf-9c4a-cbb49fecf581">\n' +
                        '      <omgdc:Font name="Arial" size="11" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" />\n' +
                        '    </bpmndi:BPMNLabelStyle>\n' +
                        '    <bpmndi:BPMNLabelStyle id="sid-84cb49fd-2f7c-44fb-8950-83c3fa153d3b">\n' +
                        '      <omgdc:Font name="Arial" size="12" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" />\n' +
                        '    </bpmndi:BPMNLabelStyle>\n' +
                        '  </bpmndi:BPMNDiagram>\n' +
                        '</definitions>'
        // 将字符串转换成图显示出来
        this.bpmnModeler.importXML(bpmnXmlStr, function (err) {
          if (err) {
            console.error(err)
          }
        })
      },
      // 下载为SVG格式,done是个函数，调用的时候传入的
      saveSVG (done) {
        // 把传入的done再传给bpmn原型的saveSVG函数调用
        this.bpmnModeler.saveSVG(done)
      },
      // 下载为SVG格式,done是个函数，调用的时候传入的
      saveDiagram (done) {
        // 把传入的done再传给bpmn原型的saveXML函数调用
        this.bpmnModeler.saveXML({ format: true }, function (err, xml) {
          done(err, xml)
        })
      },
      // 当图发生改变的时候会调用这个函数，这个data就是图的xml
      setEncoded (type) {
        // 把xml转换为URI，下载要用到的
        const encodedData = encodeURIComponent(type === 'svg' ? this.xmlStrSvg : this.xmlStrXml)
        // 获取到图的xml，保存就是把这个xml提交给后台
        // 下载图的具体操作,改变a的属性，className令a标签可点击，href令能下载，download是下载的文件的名字
        if (encodedData) {
          var url = 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData
          var bpmnName = this.bpmnModeler._definitions.rootElements[0].name
          var filename = bpmnName + '.' + type

          var a = document.createElement('a')
          a.style = 'display: none'
          a.href = url
          a.download = filename

          document.body.appendChild(a)
        }
      },
      // 保存到后台
      saveMyDiagram () {
        let param = new FormData()
        var blob = new Blob([this.xmlStrXml])
        param.append('file', blob)
        const bpmnId = this.bpmnModeler._definitions.rootElements[0].id
        param.append('key', bpmnId)
        this.$ajax.post(`/api/upload`, param)
        .then((res) => {
          this.$message({
            message: '保存成功！',
            type: 'success'
          })
          this.$router.push('/')
        })
        .catch((res) => {
          console.log(res)
          this.$message.error('保存失败！')
        })
      }
    },
    mounted () {
      // 获取到属性ref为“content”的dom节点
      this.container = this.$refs.content
      // 获取到属性ref为“canvas”的dom节点
      const canvas = this.$refs.canvas

      // 建模，官方文档这里讲的很详细
      this.bpmnModeler = new BpmnModeler({
        container: canvas,
        // 添加控制板
        propertiesPanel: {
          parent: '#js-properties-panel'
        },
        additionalModules: [
          // 左边工具栏以及节点
          propertiesProviderModule,
          // 右边的工具栏
          propertiesPanelModule,
          // 汉化
          customTranslate
        ],
        moddleExtensions: {
          camunda: camundaModdleDescriptor
        }
      })

      // 下载画图
      let _this = this
      // 获取a标签dom节点
      // 给图绑定事件，当图有发生改变就会触发这个事件
      this.bpmnModeler.on('commandStack.changed', function () {
        _this.saveSVG(function (err, svg) {
          _this.xmlStrSvg = err ? null : svg
        })

        _this.saveDiagram(function (err, xml) {
          _this.xmlStrXml = err ? null : xml
        })
      })
      this.createNewDiagram(this.bpmnModeler)
      setTimeout(() => {
        document.getElementsByName('id')[0].disabled = 'disabled'
        document.getElementsByClassName('clear')[0].style.display = 'none'
      }, 100)
    }
  }
</script>
